<?php


namespace app\tt\controller;


use app\user\model\TtUser;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\DecryptException;
use think\Controller;
use think\Exception;
use think\exception\PDOException;
use think\facade\Config;
use  think\facade\Request;

class User extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkTTUserToken::class'
    ];

    //头条的用户信息
    public function info()
    {
        $user_id = Request::param('user_id');

        $info = TtUser::get($user_id);

        //判断是否存在该用户
        if ($info == null) {
            $this->result(null, 300, '该用户不存在，请重新登录');
        } else {
            $this->result($info, 200, '获取用户资料成功');
        }
    }

    //更新用户信息
    public function update()
    {
        $data= Request::only(['avatarUrl','nickName']);
         $user_id = Request::param('user_id');
        $res = TtUser::where('id',$user_id)->update([
            'avatar'=> $data['avatarUrl'],
            'username'=> $data['nickName'],
        ]);

        $this->result($res,200,'更新成功');
    }

    //绑定微信
    public function bindWechat()
    {
        $user_id = Request::param('user_id');
        $wechat_user_id = Request::param('wechat_user_id');
        $force = Request::param('force',false);       //是否强制更新

        //获取用户的资料
        $info = TtUser::get($user_id);

        //已经绑定过了
        if($info['user_id']==$wechat_user_id){
            $this->result($info, 200, '绑定成功');
        }

        //还未绑定过
        if($info['user_id']==0){

            //进行绑定
            $res=TtUser::where(['id'=>$user_id])->update([
                'user_id'=>$wechat_user_id
            ]);

            $info['user_id']=$wechat_user_id;
            if($res){
                $this->result($info, 200, '绑定微信账号成功');
            }else{
                $this->result(null, 400, '绑定失败，请稍后再试');
            }

        }else{
            if($force){
                //进行绑定
                $res=TtUser::where(['id'=>$user_id])->update([
                    'user_id'=>$wechat_user_id
                ]);

                $info['user_id']=$wechat_user_id;
                if($res){
                    $this->result($info, 200, '绑定微信账号成功');
                }else{
                    $this->result(null, 400, '绑定失败，请稍后再试');
                }
            }else{
                $this->result(4001, 200, '已经绑定过了，是否更换？');
            }

        }

    }



}
